const db = require("../config/db");

// 分页查询热门电影
exports.getHighRatedMovies = async (req, res) => {
    try {
        const { page = 1, limit = 5 } = req.body;
        const offset = (parseInt(page) - 1) * parseInt(limit);

        // 获取电影数据
        const movieSql = `
            SELECT * FROM movies 
            WHERE rating >= 9 AND count_reviews > 1
            ORDER BY rating DESC, count_reviews DESC 
            LIMIT ? OFFSET ?
        `;
        const [movies] = await db.query(movieSql, [parseInt(limit), offset]);

        // 获取符合条件的电影总数
        const countSql = `
            SELECT COUNT(*) AS total FROM movies 
            WHERE rating >= 9 AND count_reviews > 1
        `;
        const [countResult] = await db.query(countSql);
        const total = countResult[0].total;

        res.json({
            data: movies,
            total: total,
            page: parseInt(page),
            limit: parseInt(limit)
        });
    } catch (error) {
        res.status(500).json({ error: '内部服务错误' });
    }
};

// 分页查询热门影评
exports.getHighRatedReviews = async (req, res) => {
    try {
        const { page = 1, limit = 5 } = req.body;
        const offset = (parseInt(page) - 1) * parseInt(limit);

        // 获取影评数据
        const reviewSql = `
            SELECT r.*, u.username, m.title, m.poster_url
            FROM reviews r
            JOIN users u ON r.user_id = u.id
            JOIN movies m ON r.movie_id = m.id
            WHERE r.user_rating >= 9.5 AND r.likes >= 100
            ORDER BY r.user_rating DESC, r.likes DESC 
            LIMIT ? OFFSET ?
        `;
        const [reviews] = await db.query(reviewSql, [parseInt(limit), offset]);

        // 获取符合条件的影评总数
        const countSql = `
            SELECT COUNT(*) AS total
            FROM reviews r
            JOIN users u ON r.user_id = u.id
            JOIN movies m ON r.movie_id = m.id
            WHERE r.user_rating >= 9.5 AND r.likes >= 100
        `;
        const [countResult] = await db.query(countSql);
        const total = countResult[0].total;

        res.json({
            data: reviews,
            total: total,
            page: parseInt(page),
            limit: parseInt(limit)
        });
    } catch (error) {
        res.status(500).json({ error: '内部服务错误' });
    }
};